package com.df.gamesynctest.entity;

import com.df.gamesynctest.msg.S2C_MonsterMoveTo;
import com.df.gamesynctest.net.Server;

import java.util.List;
import java.util.Random;

public class GameMapMonsterScript implements IMapObjectScript{
    private Monster ower;


    private double last9x;
    private double last9y;

    public GameMapMonsterScript(Monster ower){
        this.ower = ower;
        Vector2 vector2 = ower.map.cal9pos(ower.pos);
        last9y = vector2.y;
        last9x = vector2.x;
    }

    @Override
    public void update(double lastFrameTime) {
//        System.out.println("lastFrameTime:"+lastFrameTime);
        //四处游荡
        if(ower.moveTarget== null){
            createNewMoveTarget();
        }
        if(ower.pos.equals(ower.moveTarget)){
            createNewMoveTarget();
            return;
        }
        //移动计算
        Vector2 moveDir = ower.moveTarget.sub(ower.pos).normalize();
        Vector2 moveLen = moveDir.multiply(lastFrameTime).multiply(ower.speed);
       Vector2 movePoint =  ower.pos.plus(moveLen);
        Vector2 newDir = ower.moveTarget.sub(movePoint).normalize();
        if(newDir.equals(moveDir) || newDir.equals(new Vector2(0,0))){//未移动到目标点
           ower.pos.x = movePoint.x;
           ower.pos.y = movePoint.y;
//           System.out.println("达到新坐标："+ower.pos);
       }else{//超过目标点，则设置未目标点

           ower.pos.x = ower.moveTarget.x;
           ower.pos.y = ower.moveTarget.y;
//           System.out.println("达到目标点："+ower.pos);
       }
       //移动到新的点计算所在九宫格坐标是否变化，有的话要同步
        Vector2 vector2 =  ower.map.cal9pos(ower.pos);
       if(last9x!=vector2.x||last9y!=vector2.y){//所在九宫格发生变化
           //之前部分玩家移除视野通知
           //当前部分玩家进入视野通知
       }
    }

    private void createNewMoveTarget(){
        Random random = new Random();
        ower.moveTarget = new Vector2(random.nextInt(40)-20,random.nextInt(40)-20);
        System.out.println("更新目标点:"+ower.moveTarget);
        //同步给周围的玩家，九宫格算法
        List<Player> aroundPlayer = ower.map.findAroundPlayer(ower.pos);
        System.out.println("周围玩家："+aroundPlayer.size());
        S2C_MonsterMoveTo msg = new S2C_MonsterMoveTo();
        msg.id=  ower.id;
        msg.x = ower.moveTarget.x;
        msg.y = ower.moveTarget.y;
        UserManager.getInstance().broadCastMsg(aroundPlayer,msg);
    }
}
